import Taro from "@tarojs/taro";
import { Button, View } from "@tarojs/components";
import "./index.scss";
import { CustomRequest } from "@/utils/request";
import { useDispatch, useSelector } from "@tarojs/redux";
import { closeAvatarPermissionModal } from "@/actions/avatarPermission";

export interface IAvatarPermissionContainer {
  children: JSX.Element;
  reLaunchPath: string;
}

export const ApiPostAvatarPermission = `/weChat/wx/saveUserInfo`;

export const AvatarPermissionClickContainer = (
  props: IAvatarPermissionContainer
) => {
  const { children, reLaunchPath } = props;

  const dispatch = useDispatch();

  const userMessage = Taro.getStorageSync("avatarPermission");

  const avatarPermission = useSelector((state: any) => state.avatarPermission);
  console.log(avatarPermission);

  const getUserInfoCallback = (e: any) => {
    if (e.target.errMsg === "getUserInfo:ok") {
      const userInfo = e.target.userInfo;
      const { avatarUrl, nickName } = userInfo;
      CustomRequest.post(ApiPostAvatarPermission, { avatarUrl, nickName }).then(
        res => {
          if (res) {
            dispatch(closeAvatarPermissionModal());
            Taro.reLaunch({
              url: reLaunchPath
            });
          }
        }
      );
    }
  };
  return (
    <View className="avatar-permission-container">
      {children}
      {(userMessage === 0 && avatarPermission) || !userMessage ? (
        <Button
          openType="getUserInfo"
          className="btn"
          onGetUserInfo={getUserInfoCallback}
        ></Button>
      ) : (
        ""
      )}
    </View>
  );
};
